<!--
 * @Author: early-autumn
 * @Date: 2020-05-30 13:13:52
 * @LastEditors: early-autumn
 * @LastEditTime: 2020-05-30 16:18:37
-->
<template>
  <div class="card__container">
    <el-card v-loading="loading" shadow="hover" class="card__content">
      <h4 slot="header" class="card__header">
        <span>回访记录</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="handleVisible"
        >
          添加
        </el-button>
      </h4>
      <el-form size="mini">
        <el-form-item
          v-for="visit in visitList"
          :key="visit.id"
          :label="visit.createTime"
        >
          回访人：{{ visit.visitPerson }} 状态：{{
            trackingStatusEnum[visit.trackStatus]
          }}
          内容：{{ visit.contet }} 结果：{{ visit.result }}
        </el-form-item>
      </el-form>
    </el-card>
    <div class="card__content">
      <el-card v-if="visible" shadow="hover" class="card__content">
        <el-form ref="form" :model="form" :rules="rules" label-width="110px">
          <el-form-item label="回访时间" prop="visitTime">
            <el-date-picker
              v-model="form.visitTime"
              type="datetime"
              :picker-options="pickerOptions"
              :editable="false"
              :clearable="false"
              placeholder="选择日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="跟踪状态" prop="trackStatus">
            <el-select
              v-model="form.trackStatus"
              placeholder="请选择跟踪状态"
              style="width: 220px"
            >
              <el-option
                v-for="option in trackingStatusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="消费状态" prop="consumeStatus">
            <el-select
              v-model="form.consumeStatus"
              placeholder="请选择消费状态"
              style="width: 220px"
            >
              <el-option
                v-for="option in consumeStatusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="回访人员" prop="visitPerson">
            <el-select
              v-model="form.visitPerson"
              placeholder="请选择回访人员"
              style="width: 220px"
            >
              <el-option
                v-for="option in tcOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="回访计划" prop="contet">
            <el-input
              v-model="form.contet"
              class="card__input"
              type="textarea"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-form-item label="回访结果" prop="result">
            <el-input
              v-model="form.result"
              class="card__input"
              type="textarea"
              :rows="3"
            ></el-input>
          </el-form-item>
          <el-button
            type="primary"
            :loading="formLoading"
            @click="handleSubmit(returnVisitStatusEnum['待计划'])"
          >
            保存待计划
          </el-button>
          <el-button
            type="primary"
            :loading="formLoading"
            @click="handleSubmit(returnVisitStatusEnum['已完成'])"
          >
            完成回访
          </el-button>
          <el-button @click="handleVisible">取消</el-button>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import { addTc, listTc } from '@/api/services/tc'
import { listStaff } from '@/api/services/common'
import {
  returnVisitStatusOptions,
  trackingStatusOptions,
  consumeStatusOptions,
} from '@/utils/options'
import { returnVisitStatusEnum, trackingStatusEnum } from '@/utils/enums'

const FORM_DATA = {
  visitTime: undefined,
  trackStatus: undefined,
  consumeStatus: undefined,
  visitPerson: undefined,
  visitStatus: undefined,
  contet: undefined,
  result: undefined,
}

export default {
  name: 'ReturnVisit',
  props: {
    patient: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      loading: false,
      visible: true,
      tcList: [],
      visitList: [],
      formLoading: false,
      form: {},
      // 表单校验
      rules: {
        visitPerson: [
          { required: true, message: '回访人员不能为空', trigger: 'blur' },
        ],
        trackStatus: [
          { required: true, message: '跟踪状态不能为空', trigger: 'blur' },
        ],
        consumeStatus: [
          { required: true, message: '消费状态不能为空', trigger: 'blur' },
        ],
        contet: [
          { required: true, message: '回访内容不能为空', trigger: 'blur' },
        ],
        visitTime: [
          { required: true, message: '回访时间不能为空', trigger: 'blur' },
        ],
      },
      pickerOptions: {
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            },
          },
          {
            text: '明天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24)
              picker.$emit('pick', date)
            },
          },
          {
            text: '一周后',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            },
          },
        ],
        disabledDate: (time) => {
          return time.getTime() < Date.now() - 24 * 60 * 60 * 1000 // 返回 所有时间 大于 当前时间
        },
      },
    }
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.name,
      clinicId: (state) => state.clinic.clinicId,
      clinicName: (state) => state.clinic.clinicName,
    }),
    trackingStatusOptions() {
      return trackingStatusOptions
    },
    returnVisitStatusOptions() {
      return returnVisitStatusOptions
    },
    consumeStatusOptions() {
      return consumeStatusOptions
    },
    returnVisitStatusEnum() {
      return returnVisitStatusEnum
    },
    trackingStatusEnum() {
      return trackingStatusEnum
    },
    tcOptions() {
      return this.tcList.map(({ userName }) => ({
        label: userName,
        value: userName,
      }))
    },
  },
  watch: {
    visible(val) {
      if (val) {
        this.init()
      } else {
        this.$refs.form.resetFields()
      }
    },
  },
  mounted() {
    this.init()
    this.getTcList()
    this.getListTc()
  },
  methods: {
    init() {
      this.form = { ...FORM_DATA }
    },
    /**
     * 获取tc列表
     */
    async getTcList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })
      this.tcList = data
    },
    async getListTc() {
      try {
        this.loading = true
        const { rows } = await listTc({
          clinicPersonId: this.patient.id,
        })
        this.visitList = rows
      } finally {
        this.loading = false
      }
    },
    handleVisible() {
      this.visible = !this.visible
    },
    handleSubmit(visitStatus) {
      this.$refs.form.validate(async (valid) => {
        try {
          if (!valid) {
            return
          }
          this.formLoading = true
          const {
            id: clinicPersonId,
            caseNumber,
            name,
            phoneNumber,
          } = this.patient
          const formData = {
            ...this.form,
            visitStatus,
            visitTime: dayjs(this.form.visitTime).format('YYYY-MM-DD HH:mm:ss'),
            clinicPersonId,
            caseNumber,
            name,
            phoneNumber,
            clinicId: this.clinicId,
            clinicName: this.clinicName,
            createBy: this.userName,
          }
          if (visitStatus === returnVisitStatusEnum['已完成']) {
            formData.visitFinishTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
          }
          await addTc(formData)
          this.msgSuccess('添加成功')
          this.handleVisible()
          await this.getListTc()
        } finally {
          this.formLoading = false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.card__container {
  width: 100%;
  display: flex;

  &:first-child {
    margin-bottom: 20px;
  }

  .card__content {
    flex: 1;

    &:first-child {
      margin-right: 20px;
    }

    .card__header,
    .card__p {
      margin: 0;
    }

    .card__p,
    .card__input {
      margin-bottom: 15px;
    }

    .card__p {
      font-size: 14px;
    }
  }
}
</style>
